import { useState } from 'react';
import { useBlogStore } from '../../store';
import { useShallow } from 'zustand/react/shallow';
import { Link } from 'umi';
import {
  Card,
  CardContent,
  CardDescription,
  CardFooter,
  CardHeader,
  CardTitle,
} from '../../components/ui/card';
import { Button } from '../../components/ui/button';
import { motion } from 'framer-motion';
import usePosts from './usePosts';

export default function PostsPage() {
  const [searchText, setSearchText] = useState('');
  const [selectedTag, setSelectedTag] = useState<string | null>(null);
  const [currentPage, setCurrentPage] = useState(1);

  const pageSize = 5;

  // 使用新的 SWR hooks 获取数据
  const postsData = usePosts({
    page: currentPage,
    pageSize,
    search: searchText || undefined,
    tag: selectedTag || undefined,
  });

  // 保留 zustand 的一些状态管理功能（如果需要的话）
  const { incrementLikes: incrementLikesStore, incrementViews: incrementViewsStore } = useBlogStore(
    useShallow((state) => ({
      incrementLikes: state.incrementLikes,
      incrementViews: state.incrementViews,
    })),
  );

  // 处理点赞和浏览量
  const handleReadMore = async (postId: number) => {
    try {
      // 调用 API 更新服务器数据

      // 同时更新本地状态（可选，如果你想保持本地状态同步）
      incrementLikesStore(postId);
      incrementViewsStore(postId);
    } catch (error) {
      console.error('Failed to update post stats:', error);
      // 如果 API 调用失败，仍然更新本地状态
      incrementLikesStore(postId);
      incrementViewsStore(postId);
    }
  };

  return (
    <div className="space-y-8">
      <motion.div
        className="mb-8"
        initial={{ opacity: 0, y: 20 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ duration: 0.5 }}
      >
        <h1 className="text-3xl font-bold mb-4">博客文章</h1>
        <p className="text-gray-600 dark:text-gray-300">
          探索我的技术文章、教程和见解。使用下面的搜索和过滤选项找到你感兴趣的内容。
        </p>
      </motion.div>

      <div className="flex flex-col md:flex-row gap-4 mb-8">
        <div className="relative w-full md:w-64">
          <input
            type="text"
            placeholder="搜索文章标题或内容"
            value={searchText}
            onChange={(e) => setSearchText(e.target.value)}
            className="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 dark:bg-gray-700 dark:text-white"
          />
          <span className="absolute right-3 top-2.5 material-icons text-gray-400">search</span>
        </div>

        <div className="relative w-full md:w-64">
          <select
            value={selectedTag || ''}
            onChange={(e) => setSelectedTag(e.target.value || null)}
            className="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 appearance-none dark:bg-gray-700 dark:text-white"
          ></select>
          <span className="absolute right-3 top-2.5 material-icons text-gray-400 pointer-events-none">
            expand_more
          </span>
        </div>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
        {postsData.posts.map((post, index) => (
          <motion.div
            key={post.id}
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.3, delay: index * 0.1 }}
          >
            <Card className="h-full">
              <CardHeader>
                <CardTitle>
                  <Link to={`/post/${post.id}`} className="hover:text-blue-600 transition-colors">
                    {post.title}
                  </Link>
                </CardTitle>
                <CardDescription>{post.date}</CardDescription>
              </CardHeader>
              <CardContent>
                <p className="line-clamp-3">{post.excerpt}</p>
                <div className="flex flex-wrap gap-2 mt-3">
                  {post.tags.map((tag: string) => (
                    <span
                      key={tag}
                      className="px-2 py-1 text-xs rounded-full bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-100 cursor-pointer"
                      onClick={() => setSelectedTag(tag)}
                    >
                      {tag}
                    </span>
                  ))}
                </div>
              </CardContent>
              <CardFooter className="flex justify-between">
                <div className="flex space-x-4 text-sm text-gray-500 dark:text-gray-400">
                  <span className="flex items-center">
                    <span className="material-icons text-sm mr-1">visibility</span> {post.views}
                  </span>
                  <span className="flex items-center">
                    <span className="material-icons text-sm mr-1">favorite</span> {post.likes}
                  </span>
                </div>
                <Button variant="ghost" size="sm" onClick={() => handleReadMore(post.id)}>
                  阅读更多
                </Button>
              </CardFooter>
            </Card>
          </motion.div>
        ))}
      </div>

      <div className="flex justify-center mt-8">
        <div className="flex space-x-2">
          <Button
            variant="outline"
            onClick={() => setCurrentPage((prev) => Math.max(prev - 1, 1))}
            disabled={currentPage === 1}
          >
            上一页
          </Button>

          {Array.from({ length: postsData.totalPages }, (_, i) => i + 1).map((page) => (
            <Button
              key={page}
              variant={currentPage === page ? 'primary' : 'outline'}
              onClick={() => setCurrentPage(page)}
            >
              {page}
            </Button>
          ))}

          <Button
            variant="outline"
            onClick={() => setCurrentPage((prev) => Math.min(prev + 1, postsData.totalPages))}
            disabled={currentPage === postsData.totalPages}
          >
            下一页
          </Button>
        </div>
      </div>
    </div>
  );
}
